package com.lianjinsu.shop.service.impl;

import com.lianjinsu.shop.controller.vo.SelfStatus;
import com.lianjinsu.shop.entity.User;
import com.lianjinsu.shop.repository.dao.UserDao;
import com.lianjinsu.shop.service.UserService;
import com.lianjinsu.shop.third.forest.WechatForestClient;
import com.lianjinsu.shop.third.forest.WechatForestClient.SessionResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
    private final UserDao userDao;

    private final WechatForestClient wechatForestClient;

    @Value("${wechat.applet.appId}")
    private String appId;

    @Override
    public boolean insertOrUpdateUser(User user) {
        return user.insertOrUpdate();
    }

    @Override
    public boolean removeById(int id) {
        return userDao.removeById(id);
    }

    @Override
    public SelfStatus session(String code) {
        SessionResponse response = wechatForestClient.session(code);
        if (Objects.isNull(response) || StringUtils.isBlank(response.getOpenid())) {
            throw new RuntimeException("response is null or " + code + " " + response.getErrMsg());
        }
        User user = new User();
        user.setAppId(appId);
        user.setOpenid(response.getOpenid());
        user.setSessionKey(response.getSessionKey());
        user.setUnionId(response.getUnionId());
        user.insertOrUpdate();
        SelfStatus selfStatus = new SelfStatus();
        selfStatus.setStatus(SELF_STATUS);
        return selfStatus;
    }

    @Override
    public User user(String openId) {
        return userDao.getById(openId);
    }

    public boolean updateUser(String field, Object value, String openId) {
        return userDao.updateUser(field, value, openId);
    }
}
